package netty.pastePack;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import netty.pastePack.protocol.MessageProtocol;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @Description TODO
 * @Author 李龙平
 * @Date 2020/10/13 17:27
 */
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("服务器消息读取");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("服务器channel就绪");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext  ctx, MessageProtocol messageProtocol) throws Exception {

        int len = messageProtocol.getLen();
        byte[] content = messageProtocol.getContent();
        System.out.println("len" + len);
        System.out.println("接受到数据" + new String(content, StandardCharsets.UTF_8));
        System.out.println("服务器接收包数" + (++this.count));

        String respMsg = UUID.randomUUID().toString();
        int respLen = respMsg.length();

        MessageProtocol msg = new MessageProtocol();
        msg.setLen(respLen);
        msg.setContent(respMsg.getBytes(StandardCharsets.UTF_8));
        ctx.writeAndFlush(msg);
    }
}
